<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require 'global_default_function.php';

function writeData($database, $data, $user) {
	$getDate = date('Y-m-d');
	foreach ($data as $keys => $value ) {
		if( $keys > 0 ) {
			$wrtData = explode('	', $value);
			if( count($wrtData) == 12 ) {
				$wrtData[0]    = trim($wrtData[0]); //账户ID
				$wrtData[1]    = trim($wrtData[1]); //账户
				$wrtData[2]    = trim($wrtData[2]); //推广计划ID
				$wrtData[3]    = trim($wrtData[3]); //推广计划
				$wrtData[4]    = trim($wrtData[4]); //地域ID
				$wrtData[5]    = trim($wrtData[5]); //地域
				$wrtData[6]    = trim($wrtData[6]); //日期
				$wrtData[7]    = trim($wrtData[7]); //消费
				$wrtData[8]    = trim($wrtData[8]); //平均点击价格
				$wrtData[9]    = trim($wrtData[9]); //点击量
				$wrtData[10]   = trim($wrtData[10]); //展现量
				$wrtData[11]   = rtrim($wrtData[11], '%'); //点击率
				$datatime      = strtotime(date("{$wrtData[6]} 01:00:00"));
				$md5           = md5($wrtData[0].$wrtData[2].$wrtData[4].$wrtData[6]);
				$rebate        = empty($user['rebate']) ? 0 : $user['rebate'];
				$cash          = cashPrice($rebate, $wrtData[7]); //现金消费
				$res = $database->query("select id, rebate from cfg_area where md5 = '{$md5}' LIMIT 1");
				if( isset($res[0]['id']) ) {
					if( $getDate != $wrtData[6] ) {
						$rebate = $res[0]['rebate'];
						$cash = cashPrice($rebate, $wrtData[7]); //现金消费
					}
					$database->query( " UPDATE cfg_area SET `customerid` = '{$user['customerid']}', `contact` = '{$user['contact']}', `bazaarId` = '{$user['bazaarId']}', `campaign` = '{$wrtData[3]}', `impression` = '{$wrtData[10]}', `clicks` = '{$wrtData[9]}', `ctr` = '{$wrtData[11]}', 
					    `cpc` = '{$wrtData[8]}', `rebate` = '{$rebate}', `ctr` = '{$wrtData[7]}', `cash` = $cash, `datatime` = '{$datatime}' WHERE id = '{$res[0]['id']}'; ");
				} else {
					$database->query("INSERT INTO cfg_area ( `companyId`, `userType`, `bazaarId`, `customerid`, `contact`, `datatime`, `userid`, `username`, `campaignid`, `campaign`, `areaid`, `area`, `impression`, `clicks`, `ctr`, `cpc`, `rebate`, `cost`, `cash`, 
					`copynumber`, `copycost`, `md5` ) values (
					  '{$user['companyId']}', 1, '{$user['bazaarId']}', '{$user['customerid']}', '{$user['contact']}', '{$datatime}', '{$wrtData[0]}', '{$wrtData[1]}', '{$wrtData[2]}', '{$wrtData[3]}', '{$wrtData[4]}', '{$wrtData[5]}', 
						'{$wrtData[10]}',  '{$wrtData[9]}', '{$wrtData[11]}', '{$wrtData[8]}', '{$rebate}', '{$wrtData[7]}', '{$cash}', 0, 0, '{$md5}') " );
				}
			}
		}
	}
	updateTime($database, $user, 3);
}

run(function() use ($argv) {
	showMessage('读取百度地区数据.' );
	$config = getConfig();
	$database = new MySQL();
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}

  $userList = $database->query('SELECT `id`, `companyId`, `bazaarId`, `userid`, `username`, `password`, `token`, `customerid`, `contact`, `rebate` FROM cfg_expand where status = 1 and userType = 1');
	if ($userList === false) {
		showMessage($database->errno . ' - ' . $database->error);
		return;
	}

	foreach ($userList as $user) {
		go(function() use ($config, $user)  {
			$database = new MySQL();
			$connect = $database->connect($config);
			if( $connect === false) {
				return;
			}
			showMessage($user['username'].'请求地区报告数据.' );
			$reportId = getProfessionalReportId(json_encode ( [ 'header'=> [ 'username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token'] ],
			  'body'=> ['reportRequestType'=> ['performanceData'=> ['cost', 'cpc', 'click', 'impression', 'ctr' ], 'levelOfDetails'=> 3,
				  'startDate'=> date("Y-m-d", strtotime("-1 day")), 'endDate'=> date("Y-m-d", strtotime("-1 day")), 'unitOfTime'=> 5, 'reportType'=> 3, 'statRange' => 3, 'attributes'=> null, 'device' => 2 ]] ] ));
			if( $reportId['code'] == 403 ) {
				showMessage($reportId['data']);
				return;
			}
			showMessage($user['username'].'读取地区报告状态.' );
			$reportFilePath = getReportFileUrl($user, $reportId['data']->reportId);
			if(!$reportFilePath) {
				showMessage($user['username'].'请求地区报告超时.' );
				return;
			}
			showMessage($user['username'].'地区报告下载地址: ' . $reportFilePath );
			$reportFiles = getReportFiles($reportFilePath);
			if( $reportFiles === false ) {
				updateTime($database, $user, 3);
				showMessage($user['username'].'地区报告暂无数据.' );
				return;
			}
			writeData($database, $reportFiles, $user);
		});
		Swoole\Coroutine::sleep(0.5);
	}
});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');